﻿using iTool.SQL.Analysis.Context;
using iTool.SQL.Analysis.Context.Options;
using iTool.SQL.Analysis.Context.SQLWhereOptions;

using Microsoft.SqlServer.Management.SqlParser.SqlCodeDom;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace iTool.SQL.Analysis.WhereClause
{
    public class SqlBetweenBooleanExpressionAnalysis : SqlAnalysisBase
    {
        public SqlBetweenBooleanExpressionAnalysis(SqlAnalysisContext context) : base(context)
        {
        }

        public override void Analysis()
        {
            //StringBuilder where = base.GetWhereBuilder();

            var expression = (SqlBetweenBooleanExpression)base.CodeObject;
            var list = base.CodeObject.Children.ToList();

            var groupWheres = base.GetGroupWhere();
            WhereOptions whereOptions = new WhereOptions();
            SubWhereOptions sub = null;
            whereOptions.Parent = base.WhereOptions;

            if (base.WhereOptions is GroupWhereOptions group)
            {
                group.Wheres.Add(whereOptions);
            }
            else if (base.WhereOptions is SubWhereOptions)
            {
                sub = (SubWhereOptions)base.WhereOptions;
                // sub.Wheres[^1] is group
                if (sub.Wheres.Count == 0)
                {
                    sub.Wheres.Add(new GroupWhereOptions());
                }
                sub.Wheres[^1].Wheres.Add(whereOptions);
            }
            else
            {
                groupWheres[^1].Wheres.Add(whereOptions);
            }

            whereOptions.Right = new BetweenValueOptions();
            whereOptions.ComparisonBooleanExpressionType = expression.HasNot ? ComparisonBooleanExpressionType.NotBetween : ComparisonBooleanExpressionType.Between;

            base.Next(afterAction: (index, _, analysis) =>
            {
                //string nbsp = string.Empty;
                //switch (index)
                //{
                //    case 0:
                //        if (list[index + 1] is SqlLiteralExpression)
                //            nbsp = " ";
                //        where.Append(expression.HasNot ? " not between" + nbsp : " between" + nbsp);
                //        break;
                //    case 1:
                //        if (list[index + 1] is SqlLiteralExpression)
                //            nbsp = " ";
                //        where.Append(" and" + nbsp);
                //        break;
                //}
            }, whereProperty: whereOptions.Right, whereOptions: whereOptions);
        }

        public override bool Validation(SqlCodeObject codeObject) => true;
    }
}
